﻿using Microsoft.EntityFrameworkCore.Metadata.Internal;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using ZFB.Common;
using ZFB.DTO;
using ZFB.IServices;
using ZFB.Models;
using ZFB.Models.EntityConfig;
using ZFB.Repository.IdName;

namespace ZFB.Services
{
    public class IdNameServices : IIdNameServices
    {
        private readonly IIdNameRepository idNameRepository;
        public static List<IdNameDTO> idNameDTOs;
        public IdNameServices(IIdNameRepository idNameRepository, MyDbContext myDb)
        { 
            this.idNameRepository = idNameRepository;
            var data = idNameRepository.GetListAsync().Result;
            idNameDTOs = data.Select(e => new IdNameDTO
            {
                Id = e.Id,
                Name = e.Name,
                TypeName = e.TypeName
            }).ToList();
        }
        public async Task<ApiResult> AddNewAsync(IdNameEnum typeName, string name)
        {
            if (await idNameRepository.IsExistAsync(e => e.TypeName == typeName.ToString() && e.Name == name))
                return new(name+"已存在");
             var data = new T_IdNames
                {
                    Name = name,
                    TypeName = typeName.ToString()
                };
              var res= await idNameRepository.AddAsync(data);
              return res <= 0 ? new ApiResult("添加失败！") : new ApiResult();
        }

        public async Task<ApiResult> GetAllAsync(IdNameEnum typeName)
        {
          var data= idNameDTOs.Where(e=>e.TypeName==typeName.ToString()).ToList();
            return new ApiResult(data);
        }

        public async Task<ApiResult> GetByIdAsync(long id)
        {
            var data = idNameDTOs.Where(e => e.Id == id).SingleOrDefault().Name;
            return new ApiResult(data);
        }
    }
}
